<template>
<!-- <div class="app-view-container">
  <mu-flexbox orient="vertical" :gutter="0" style="height:100%">
    <mu-flexbox-item grow="0">
    </mu-flexbox-item>
    <mu-flexbox-item grow="0" class="app-tabs">
      <mu-tabs :value="activeTab" @change="handleTabChange">
        <mu-tab value="0" title="编辑"/>
        <mu-tab value="1" title="上传"/>
      </mu-tabs>
    </mu-flexbox-item>
    <mu-flexbox-item class="app-content" ref="scrollContainer">
        <div v-if="activeTab==0" style="overflow: auto">
           <mu-refresh-control :refreshing="refreshing" :trigger="trigger" @refresh="getData"/>
           <mu-list class="app-list">
             <mu-sub-header><mu-icon value="library_books"/>{{$route.query.title}}</mu-sub-header>
           </mu-list>
           <mu-list class="app-list">
             <app-file-list :list="filelist" @click="handleClick" @click.native.prevent="" :gallery="false"></app-file-list>
             <mu-raised-button v-if="!loading&&!refreshing&&currentPage<totalPage" fullWidth label="加载更多" @click="loadMore"/>
           </mu-list>
           <mu-infinite-scroll v-show="!refreshing" :scroller="scroller" :loading="loading" @load="loadMore"/>
        </div>
        <div v-if="activeTab==1">
        </div>
    </mu-flexbox-item>
  </mu-flexbox>
  <mu-bottom-sheet :open="bottomSheet" @close="closeBottomSheet">
    <mu-list @itemClick="closeBottomSheet" v-show="!eidting">
      <mu-sub-header>操作：<template v-for="o,j in actionTarget"><span v-show="j!==0">,</span>{{o.baseFileName}}</template></mu-sub-header>
      <mu-list-item v-show="actionTarget.length==1&&actionTarget[0].pattern&&actionTarget[0].bigPattern" @click="viewPhoto" title="预览"/>
      <mu-list-item v-show="actionTarget.length==1" ref="eidtAction" @click="editFile" title="编辑"/>
      <mu-list-item v-show="actionTarget.length==1" @click="downloadFile" title="下载"/>
      <mu-list-item @click="deleteFile" title="删除"/>
      <mu-list-item title="取消"/>
    </mu-list>
    <mu-list class="my-select-box-list" v-if="eidting">
      <mu-sub-header>编辑：{{actionTarget[0].baseFileName}}</mu-sub-header>
        <mu-text-field v-model="actionTarget[0].fileNo" hintText="序号" fullWidth :underlineShow="false" class="item-insert"/>
        <mu-list-item disableRipple title="开放">
          <mu-switch :value="actionTarget[0].status==1" @change="actionTarget[0].status=arguments[0]?1:0" slot="right"/>
        </mu-list-item>
        <mu-list-item disableRipple title="允许他人操作">
          <mu-switch :value="actionTarget[0].controlStatus==1" @change="actionTarget[0].controlStatus=arguments[0]?1:0"  slot="right"/>
        </mu-list-item>
    </mu-list>
    <div class="my-input-box-btns" v-show="eidting">
        <mu-raised-button label="确定" @click="save" primary/>
        <mu-raised-button label="取消" @click="eidting=false,closeBottomSheet()"/>
    </div>
  </mu-bottom-sheet>
</div> -->

<div class="app-view-container page-files">
  <mu-appbar class="app-popup-topbar">
    <mu-raised-button  class="size-s" label="返回" slot="left" @click="$router.back()"/>
    <mu-raised-button v-if="!multiSelect&&activeTab==0" class="size-s" primary label="批量操作" slot="right" @click="multiSelect=true"/>
    <mu-raised-button v-if="multiSelect" class="size-s" label="取消" slot="" @click="closeBottomSheet"/>
    <mu-raised-button v-if="multiSelect" class="size-s" primary label="全选" slot="" @click="selectAll"/>
    <mu-raised-button v-if="multiSelect" :disabled="actionTarget.length==0?true:false" class="size-s" primary label="操作" slot="right" @click="bottomSheet=true"/>
  </mu-appbar>
  <div class="app-tabs">
     <mu-tabs :value="activeTab" @change="handleTabChange">
      <mu-tab value="0" title="编辑"/>
      <mu-tab value="1" title="上传"/>
    </mu-tabs>
  </div>
  <div class="app-popup-content" ref="scrollContainer" v-show="activeTab==0">
    <mu-refresh-control :refreshing="refreshing" :trigger="trigger" @refresh="getData"/>
    <mu-list class="app-list">
      <mu-sub-header><mu-icon value="library_books"/>{{$route.query.title}}</mu-sub-header>
    </mu-list>
    <mu-list class="app-list">
      <app-file-list ref="appFileList" :class="{selectable:multiSelect}" :list="filelist" @click="handleClick" @click.native.prevent="" :gallery="false"></app-file-list>
      <mu-raised-button v-if="!loading&&!refreshing&&currentPage<totalPage" fullWidth label="加载更多" @click="loadMore"/>
    </mu-list>
    <mu-infinite-scroll v-show="!refreshing" :scroller="scroller" :loading="loading" @load="loadMore"/>
  </div>
  <div class="app-popup-content" ref="scrollContainer" v-if="activeTab==1">
    <mu-list class="app-list">
      <mu-sub-header>全文上传</mu-sub-header>
    </mu-list>
     <my-webuploader ref="uploader" :rotatable="false" :config="{
       server:uploadTextFileUrl,
       formData:{
            fileSynthesisId:this.$route.params.id,
            isPerson:this.$route.params.isPerson,
            ownerId:this.$route.params.ownerId
        },
       compress:{//压缩，仅支持jpeg
         width:1600,
         height:1600,
         quality:80,
         allowMagnify: false,
         crop: false,
         compressSize:40
       },
       uploadAccept:uploadAccept
       }" @uploadSuccess="uploadSuccess" @uploadBeforeSend="uploadBeforeSend"></my-webuploader>
  </div>
  <mu-bottom-sheet :open="bottomSheet" @close="closeBottomSheet">
    <mu-list v-show="!eidting">
      <mu-sub-header>操作：<template v-for="o,j in actionTarget"><span v-show="j!==0">,</span>{{o.baseFileName}}</template></mu-sub-header>
      <mu-list-item v-show="actionTarget.length==1&&actionTarget[0].pattern&&actionTarget[0].bigPattern" @click="viewPhoto" title="预览"/>
      <mu-list-item v-show="actionTarget.length==1" ref="eidtAction" @click="editFile" title="编辑"/>
      <mu-list-item @click="deleteFile" title="删除"/>
      <mu-list-item @click="closeBottomSheet"  title="取消"/>
    </mu-list>
    <mu-list class="my-select-box-list" v-if="eidting">
      <mu-sub-header>编辑：{{actionTarget[0].baseFileName}}</mu-sub-header>

        <mu-list-item disableRipple title="开放">
          <mu-switch :value="actionTarget[0].status==1" @change="actionTarget[0].status=arguments[0]?1:0" slot="right"/>
        </mu-list-item>
        <mu-list-item disableRipple title="允许他人操作">
          <mu-switch :value="actionTarget[0].controlStatus==1" @change="actionTarget[0].controlStatus=arguments[0]?1:0"  slot="right"/>
        </mu-list-item>
    </mu-list>
    <div class="my-input-box-btns" v-show="eidting">
        <mu-raised-button label="确定" @click="save" primary/>
        <mu-raised-button label="取消" @click="eidting=false,closeBottomSheet()"/>
    </div>
  </mu-bottom-sheet>
  <mu-dialog :open="dialog" title="警告" @close="closeDialog">
    是否要删除选中的{{actionTarget.length}}项？
    <mu-flat-button slot="actions" @click="closeDialog" primary label="取消"/>
    <mu-flat-button slot="actions" primary @click="submitDel" label="确定"/>
  </mu-dialog>
</div>
</template>

<script>
  import services from 'services'
  export default {
    data:function() {
      return {
        list:[],
        title:'',
        currentPage:0,
        totalPage:1,
        loading: false,
        scroller: null,
        refreshing: false,
        trigger: null,
        bottomSheet:false,
        actionTarget:[],  //操作对象集合
        multiSelect:false, //是否使用多选操作
        eidting:false, //是否处在编辑状态
        activeTab:'0',
        newFile:{fileNo:'',status:0,controlStatus:0},
        dialog:false,
        uploadTextFileUrl:services.ArchiveService.uploadTextFileUrl
      }
    },
    computed:{
      filelist (){
        return this.list.map(function(x){
          return {id:x.textFileId,name:x.baseFileName||'',thumb:x.pattern||'',src:x.bigPattern||''} })
      },
    },
    components:{
      'my-webuploader':(resolve)=>{require(['components/myWebuploader/myWebuploader'],resolve)}
    },
    mounted:function() {
      this.scroller = this.$refs.scrollContainer;
      this.trigger = this.$refs.scrollContainer;
      this.getData();
    },
    beforeRouteUpdate (to,form,next){
      this.getData();
      next()
    },
    methods:{
      getData (){
        this.refreshing = true
        this.currentPage=0;
        this.list=[];
        this.loadMore ()
      },
      loadMore (){
        var vm=this;
        if (vm.currentPage>=vm.totalPage&&vm.totalPage!==0||vm.loading) return
        vm.loading = true
        
        //文件列表
        services.ArchiveService.getFiles({
          data:{
            ownerId:this.$route.params.ownerId,
            fileSynthesisId:this.$route.params.id,
            currentPage:vm.currentPage+1,
            pageSize:10
          },
          success:(data)=>{
            vm.currentPage==0&&(vm.list=[])
            vm.list=vm.list.concat(data.aaData);
            vm.totalPage=data.totalPage;
            vm.currentPage++
          },
          complete:()=>{
            vm.loading = false
            vm.refreshing = false
          }
        })
      },
      handleClick(itemData){
        //选择操作对象
        if (!this.multiSelect) { 
          this.bottomSheet=true;
          this.actionTarget=[] 
        }
        var target=this.actionTarget.filter((x)=>x.textFileId==itemData.id)
        if (target.length===0) {
          this.actionTarget.push({...this.list.filter((x)=>x.textFileId==itemData.id)[0]})
        }else{
          //删除选中
          var index=this.getIndex(target[0],this.actionTarget)
          this.actionTarget.splice(index,1)
        }
      },
      selectAll(){
        // 全选
        this.actionTarget=[]
        this.actionTarget=this.actionTarget.concat(this.list)
      },
      closeBottomSheet(){
        this.actionTarget.splice(0,this.actionTarget.length)
        this.multiSelect=false
        this.eidting=false
        this.bottomSheet=false
      },
      viewPhoto (){
        //图片预览
        var vm=this;
         require(['jquery'],function(jquery){
           window.$=window.jQuery=jquery
           require(['assets/libs/fancybox/jquery.fancybox.min.css','assets/libs/fancybox/jquery.fancybox.min.js'],function(){
             var data=vm.filelist.filter((x)=>x.src&&x.thumb).map((x)=>{return {src:x.src,caption:x.name}})
             var index=vm.getIndex(vm.actionTarget[0],vm.list)
             $.fancybox.open(data,index);
             vm.closeBottomSheet()
           })
         })
      },

      deleteFile(){
        this.dialog = true
      },
      closeDialog(){
        this.dialog = false
        this.closeBottomSheet()
      },
      submitDel(){
        var vm=this;
        //删除文件
        vm.setLoading(true)
        var ids=[];
        for(var obj of vm.actionTarget)
          ids.push(obj.textFileId)
        services.ArchiveService.deleteFile({
          data:{
            ids:ids,
            isPerson:this.$route.params.isPerson,
            ownerId:this.actionTarget[0].ownerId
          },
          success:(data)=>{
            var index=-1;
            for(var obj2 of vm.actionTarget){
              index=vm.getIndex(obj2,vm.list);
              if (index>-1) vm.list.splice(index,1) 
            }
            vm.closeDialog()
            vm.showToast('删除成功',1000)
          },
          error:(data)=>{
            vm.closeDialog()
            vm.showToast('删除失败[无操作权限]',1000)
          },
          complete:()=>{
            vm.setLoading(false)
          }
        })        
      },
      editFile (){
        this.eidting=true;
      },
      save (){
        var vm=this;
        if (vm.actionTarget[0].fileNo==''){
           vm.showToast('序号不能为空') 
           return;
        }
        //编辑文件
        vm.setLoading(true)
        services.ArchiveService.editFile({
          data:{
            textFileId:this.actionTarget[0].textFileId,
            controlStatus:this.actionTarget[0].controlStatus,
            status:this.actionTarget[0].status,
            isPerson:this.$route.params.isPerson,
            ownerId:this.actionTarget[0].ownerId
          },
          success:(data)=>{
            for(var i=0; i < vm.list.length;i++)
              if (vm.list[i].textFileId==vm.actionTarget[0].textFileId) {
                vm.list.splice(i,1,vm.actionTarget[0])
                break
              }
            vm.eidting=false;
            vm.closeBottomSheet();
            vm.showToast('修改成功',1000)
          },
          error:(data)=>{
            vm.showToast('修改失败[无操作权限]',1000)
          },
          complete:()=>{
            vm.setLoading(false)
          }
        })
        
      },
      getIndex(data,datalist){
        //获取选中文件的index
        var index=-1;
        for(var i=0;i<datalist.length;i++){
          if (datalist[i].textFileId==data.textFileId) {
            index=i;
            break
          }
        }
        return index
      },
      uploadBeforeSend (o,data,headers){
        //添加额外数据
      
      },
      uploadSuccess (file,res){
        this.showToast('上传成功')
        //清空
        this.newFile={};
        for(var file of this.$refs.uploader.uploader.getFiles()){
          this.$refs.uploader.removeFile(file)
        }
      },
      uploadAccept (o,ret){
        //根据服务器返回值判断成功与否
        if(ret&&(ret.state=='y'||ret.state=='Y'))
          return true
        return false
      },
      handleTabChange (val) {
        //tab切换
        this.activeTab = val
      },
      setLoading (isLoading){  this.$store.dispatch('setLoading',isLoading) },
      showToast (toastText,time,callback){  this.$store.dispatch('showToast',{toastText,time,callback}) },
      hideToast (){  this.$store.dispatch('hideToast') }
    },
    watch:{
      actionTarget(val){
        var items=this.$refs.appFileList.$el.children
        for(var item of items)
          item.classList.remove('selected')
        for (var data of val) {
          items[this.getIndex(data,this.list)].classList.add('selected')
        }
      }
    }
  }
</script>

<style>
.page-files .app-popup-content{top: 87px;}
.page-files .selectable.app-file-list .app-file-list-item{border: 1px dashed #ccc}
.page-files .selectable.app-file-list .app-file-list-item.selected{border-color:#3a90b7;}
.page-files .mu-sub-header{    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    word-wrap: normal;}

</style>
